import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description:
 * @title: ProdConsumer_TraditionDemo
 * @author: zp
 * @date: 2021/8/2 20:25
 * 两个线程 交替操作 一个加一 一个减一 来5轮
 */
class ShareDate{
    private int mun=0;
    private Lock lock=new ReentrantLock();
    private Condition condition=lock.newCondition();

    public void add(){
        lock.lock();
        try {
            while (mun != 0){
                //线程等待
                condition.await();
            }
            mun++;
            System.out.println(mun);
            //唤醒线程
            condition.signalAll();
        }catch (Exception e){
            e.getStackTrace();
        }finally {
            lock.unlock();
        }

    }

    public void ave(){
        lock.lock();
        try {
            while (mun == 0){
                //线程等待
                condition.await();
            }
            mun--;
            System.out.println(mun);
            //唤醒线程
            condition.signalAll();
        }catch (Exception e){
            e.getStackTrace();
        }finally {
            lock.unlock();
        }
    }


}
/**
 * @description:
 * @author: zp
 * @date: 2021/8/5 21:00
 * @param: null
 * @return: 
 */
public class ProdConsumerTraditionDemo {

    public static void main(String[] args){
        ShareDate shareDate = new ShareDate();
        for (int i = 0; i <5 ; i++) {
            new Thread(()->{
                try {
                    shareDate.ave();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            },"aaa").start();
        }

        for (int i = 0; i <5 ; i++) {
            new Thread(()->{
                try {
                    shareDate.add();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            },"bbb").start();
        }

    }
}

